package com.ykq.order.controller;

import com.alibaba.fastjson.JSON;
import com.ykq.Order;
import com.ykq.Product;
import com.ykq.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Random;

//@RestController
//@RequestMapping("order")
@Slf4j
public class OrderController0 {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient; //该接口的作用: 获取注册中心中的服务清单。

    @GetMapping("createOrder/{pid}")
    public String createOrder(@PathVariable("pid")Integer pid, HttpServletRequest request){
        System.out.println(request.getRemoteAddr());
        log.info("下单开始~~~~~~~~~~~~~~~~~~~~~~~~~");
        Order order=new Order();
        order.setUid(1);
        order.setUsername("张三");
        order.setNumber(1);
        //需要调用shop-product服务的接口? 服务之间如何调用。 restTemplate====>rest的模块 基于restful的形式来调用
        log.info("调用远程查询商品接口~~~~~~~~~~~~~~~~");
        //获取注册中心中服务名shop-product的微服务信息。（ip,port）
        List<ServiceInstance> instances = discoveryClient.getInstances("shop-product");
        int i = new Random().nextInt(instances.size());
        ServiceInstance instance = instances.get(i);
        String uri = instance.getUri().toString();////保护ip+port
        Product product = restTemplate.getForObject(uri+"/product/findById/" + pid, Product.class);
        log.info("返回商品信息："+ JSON.toJSONString(product));
        order.setPprice(product.getPprice());
        order.setPname(product.getPname());
        order.setPid(product.getPid());

        orderService.createOrder(order);
        return "下单成功";
    }
}
